package com.superdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.superdp.dto.Result;
import com.superdp.dto.ScrollResult;
import com.superdp.dto.UserDTO;
import com.superdp.entity.Blog;
import com.superdp.entity.Follow;
import com.superdp.entity.User;
import com.superdp.mapper.BlogMapper;
import com.superdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.superdp.service.IFollowService;
import com.superdp.service.IUserService;
import com.superdp.utils.SystemConstants;
import com.superdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.superdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    IFollowService followService;

    @Override
    public Result queryHotBlog(int current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryById(Long id) {
        //1.查询blog
        Blog blog = getById(id);
        //2.封装blog
        if(blog==null){
            return Result.fail("笔记不存在！");
        }
        queryBlogUser(blog);
        //3。查询当前登录用户是否已经点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user==null){
            //用户未登录，无需查询是否点赞
            return;
        }
        //1.获取用户id
        Long userId = user.getId();
        //2.判断用户是否点赞
        String key="blog:liked:"+blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //设置isLiked字段，点赞过了的话设置为true
        blog.setIsLike(score!=null);
    }

    @Override
    public Result likeBlog(Long id) {
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();
        //2.判断用户是否点赞
        String key=BLOG_LIKED_KEY+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //3.未点赞的话可以点赞
        if(score==null){
            //3.1 更新数据库
            boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            if(isSuccess){
                //3.2 保存用户到set集合中
                stringRedisTemplate.opsForZSet().add(key,userId.toString(), System.currentTimeMillis());
            }
        }else {
            //4.点赞过了的话就取消点赞
            boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
            if(isSuccess){
                //3.2 保存用户到set集合中
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 根据点赞时间先后实现点赞排行榜
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String key=BLOG_LIKED_KEY+id;
        //1.查询top5点赞用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5==null||top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //2.解析出其中的id，将String转成Long
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //将id以逗号拼接
        String idStr= StrUtil.join(",",ids);
        //3.根据ids查出各个用户并转成UserDTO  WHERE ID IN(5,1) ORDER BY FIELD(ID,5,1)
        List<UserDTO> userDTOS = userService.query()
                .in("id",ids)
                .last("ORDER BY FIELD(id,"+idStr+")")
                .list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //4。返回
        return Result.ok(userDTOS);
    }

    /**
     * 保存blog并推送给每个粉丝
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        //1.获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //2.保存博客
        blog.setUserId(userId);
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("新增笔记失败!");
        }
        //3.查询当前用户的所有粉丝 select follow_user_id from tb_follow where follow_user_id=?
        List<Follow> fans = followService.query().eq("follow_user_id", userId).list();
        //4.给每个粉丝推送
        for(Follow fan :fans){
            Long fanId = fan.getUserId();
            String key="feed:"+fanId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    /**
     * 滚动分页查询
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogWithFollow(Long max, Integer offset) {
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();
        String key="feed:"+userId;
        //2.根据用户id查询redis ZREVRANGEBYSCORE KEY Max Min LIMIT offset count,java中先min再max
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        // 2.1非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //3.解析数据:blogId,minTime,os
        //minTime为本次查询最小的值，下一次查询从这个最小值的下一个开始，os是偏移量，如果本次最小的值有相同情况，则将偏移量+1
        List<Long> blogIds =new ArrayList<>(typedTuples.size());
        long minTime=0;//5 4 4 2 2
        int os=1;//1 1 2 1 2
        for (ZSetOperations.TypedTuple<String> tuple:typedTuples){//5 4 4 2 2
            blogIds.add(Long.valueOf(tuple.getValue()));
            long time=tuple.getScore().longValue();
            if(minTime==time){
                os++;
            }else {
                minTime=time;
                os=1;
            }
        }
        os = minTime == max ? os : os + offset;
        //4.根据blogId查询blog
        String ids= StrUtil.join(",",blogIds);
        List<Blog> blogs = query().in("id", blogIds).last("ORDER BY FIELD(id," + ids + ")").list();
        for(Blog blog:blogs){
            //4.1查询blog有关用户
            queryBlogUser(blog);
            //4.2查询当前登录用户是否已经点赞
            isBlogLiked(blog);
        }
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setMinTime(minTime);
        r.setOffset(os);
        return Result.ok(r);

    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}

